/*
 *  Copyright 2015-2016, RenGu Technology (BeiJing) Co., Ltd.
 *  All right reserved.
 *
 *  THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF RENGU TECHNOLOGY (BeiJing) CO., LTD.
 *
 *  THE CONTENTS OF THIS FILE MAY NOT BE DISCLOSED TO THIR PARTIES,
 *  COPIED OR DUPLICATED IN ANY FORM, IN WHOLE OR IN PART,
 *  WITHOUT THE PRIOR WRITTEN PERMISSION OF RENGU TECHNOLOGY (BeiJing) CO., LTD.
 *
 *  NcqsIntelligenceCreditServiceImpl
 *
 *  Edit History:
 *      wukefan Created on 2020年08月19日
 *
 */
package cc.rengu.igas.route.core.realize.credit.impl.ncqs;

import cc.rengu.igas.channel.ncqs.biz.impl.NcqsPayServiceImpl;
import cc.rengu.igas.channel.ncqs.facade.base.Header;
import cc.rengu.igas.channel.ncqs.facade.bean.RiskInfo;
import cc.rengu.igas.channel.ncqs.facade.request.NcqsCreditPayAcqRequest;
import cc.rengu.igas.channel.ncqs.facade.response.NcqsCreditPayAcqResponse;
import cc.rengu.igas.channel.ncqs.facade.result.Result;
import cc.rengu.igas.route.common.constant.SmartRouteParamConstant;
import cc.rengu.igas.route.common.enums.SmartRouteRspEnums;
import cc.rengu.igas.route.core.realize.credit.DstChannelCreditService;
import cc.rengu.igas.route.facade.request.IntelligenceCreditRequest;
import cc.rengu.igas.route.facade.request.IntelligenceResultQueryRequest;
import cc.rengu.igas.route.facade.response.IntelligenceCreditResponse;
import cc.rengu.igas.route.facade.response.IntelligenceResultQueryResponse;
import cc.rengu.igas.share.common.constant.ShareParamConstant;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.common.enums.AcctTypeEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 无卡快捷代付
 *
 * @author lizhangtao
 * @version 1.0
 * @date 2020/8/19
 */
public class NcqsCreditServiceImpl implements DstChannelCreditService {
    private final static String TXN_NUM = "2001";
    private RgLogger rglog = RgLog.getLogger(this.getClass().getSimpleName());

    @Override
    public IntelligenceCreditResponse credit(IntelligenceCreditRequest intelligenceCreditRequest) throws Exception {
        NcqsCreditPayAcqRequest ncqsCreditPayAcqRequest = new NcqsCreditPayAcqRequest();
        IntelligenceCreditResponse intelligenceCreditResponse = new IntelligenceCreditResponse();
        intelligenceCreditResponse.setHeader(intelligenceCreditRequest.getHeader());
        intelligenceCreditResponse.setDstChannelTxnNum(TXN_NUM);
        ncqsCreditPayAcqRequest.setMchntType("4816");
        //商户号补充到15位
        if (intelligenceCreditRequest.getMchntNo().length() < 15) {
            ncqsCreditPayAcqRequest.setCupsMchntNo(intelligenceCreditRequest.getMchntNo() + String.format("%0" + (15 - intelligenceCreditRequest.getMchntNo().length()) + "d", 0));
        } else if (intelligenceCreditRequest.getMchntNo().length() > 15) {
            ncqsCreditPayAcqRequest.setCupsMchntNo(intelligenceCreditRequest.getMchntNo().substring(intelligenceCreditRequest.getMchntNo().length() - 15));
        } else {
            ncqsCreditPayAcqRequest.setCupsMchntNo(intelligenceCreditRequest.getMchntNo());
        }
        ncqsCreditPayAcqRequest.setMchntName(intelligenceCreditRequest.getMchntName());
        //从业务类型转换来
        ncqsCreditPayAcqRequest.setBusiType("100003");
        //全额消费
        ncqsCreditPayAcqRequest.setBusiFuncType("311011");
        ncqsCreditPayAcqRequest.setPayeeAcctNo(intelligenceCreditRequest.getPayeeInfo().getAcctNo());
        ncqsCreditPayAcqRequest.setPayeeAcctName(intelligenceCreditRequest.getPayeeInfo().getAcctName());
        ncqsCreditPayAcqRequest.setPayeeAcctIssrId(intelligenceCreditRequest.getPayeeInfo().getOpenBankNo());
        //单位结算卡
        if (AcctTypeEnum.OTHER_PUB_ACCT.getAcctType().equals(intelligenceCreditRequest.getPayerInfo().getAcctType())) {
            ncqsCreditPayAcqRequest.setCorpName(intelligenceCreditRequest.getPayerInfo().getAcctName());
            //单位结算卡证件id填写营业执照号
            ncqsCreditPayAcqRequest.setLicenceNo(intelligenceCreditRequest.getPayerInfo().getCertId());
        } else {
            ncqsCreditPayAcqRequest.setPayAcctName(intelligenceCreditRequest.getPayerInfo().getAcctName());
            ncqsCreditPayAcqRequest.setPayAcctNo(intelligenceCreditRequest.getPayerInfo().getAcctNo());
            ncqsCreditPayAcqRequest.setCertType(intelligenceCreditRequest.getPayerInfo().getCertType());
            ncqsCreditPayAcqRequest.setCertNo(intelligenceCreditRequest.getPayerInfo().getCertId());
        }
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(intelligenceCreditRequest.getHeader().getInstId(), SmartRouteParamConstant.OPMS_SYS_PARAM, SmartRouteParamConstant.NCQS_INST_CODE);
        if (null == sysParam || StringUtil.isEmptyOrNull(sysParam.getParamValue())) {
            rglog.error("未获取到<{}>机构转换为银联无卡快捷数据或者机构转换数据不存在", intelligenceCreditRequest.getHeader().getInstId());
            throw new BizException(SmartRouteRspEnums.CONFIG_ERROR.getRespCode(), SmartRouteRspEnums.CONFIG_ERROR.getRespDesc());
        }
        ncqsCreditPayAcqRequest.setCupsInstCode(sysParam.getParamValue());
        ncqsCreditPayAcqRequest.setTermType("07");
        RiskInfo riskInfo = new RiskInfo();
        ncqsCreditPayAcqRequest.setRiskInfo(riskInfo);
        ncqsCreditPayAcqRequest.setOrderId(intelligenceCreditRequest.getHeader().getTraceNo());
        //设置请求头
        Header header = new Header();
        BeanUtil.beanCopy(intelligenceCreditRequest.getHeader(), header);
        header.setTxnNum(TXN_NUM);
        if (!StringUtil.isEmptyOrNull(intelligenceCreditRequest.getAdditionInfo())) {
            JSONObject jsonObject = JSON.parseObject(intelligenceCreditRequest.getAdditionInfo());
            if (null != jsonObject) {
                String esbSequenceNumber = jsonObject.getString(ShareParamConstant.ESB_SEQUENCE_NUMBER);
                if (!StringUtil.isEmptyOrNull(esbSequenceNumber)) {
                    header.setTraceNo(esbSequenceNumber);
                }
            }
        }
        ncqsCreditPayAcqRequest.setHeader(header);
        ncqsCreditPayAcqRequest.setNcqsReserve(intelligenceCreditRequest.getAdditionInfo());
        //调用通道签约
        DubboService dubboService = new DubboServiceImpl();
        Result<NcqsCreditPayAcqResponse> ncqsCreditPayAcqResponseResult = (Result<NcqsCreditPayAcqResponse>)
                dubboService.callDubboInnerMethod(NcqsPayServiceImpl.class, "creditPay", ncqsCreditPayAcqRequest);
        if (!ncqsCreditPayAcqResponseResult.isSuccess() || null == ncqsCreditPayAcqResponseResult.getResult()) {
            rglog.error("交易未应答信息");
            throw new BizException(SmartRouteRspEnums.TRANS_TO.getRespCode(), SmartRouteRspEnums.TRANS_TO.getRespDesc());
        }
        intelligenceCreditResponse.setRespCode(ncqsCreditPayAcqResponseResult.getResult().getRespCode());
        intelligenceCreditResponse.setRespDesc(ncqsCreditPayAcqResponseResult.getResult().getRespDesc());
        intelligenceCreditResponse.setDstChannelId("NCQS");
        if (OltpRpcdEnum.TRANS_SUCCESS.getRespCode().equals(ncqsCreditPayAcqResponseResult.getResult().getRespCode())) {
            intelligenceCreditResponse.setDstChannelSsn(ncqsCreditPayAcqResponseResult.getResult().getSettleKey());
            intelligenceCreditResponse.setSettleDate(ncqsCreditPayAcqResponseResult.getResult().getSettleDate());
        }
        return intelligenceCreditResponse;
    }

    @Override
    public IntelligenceResultQueryResponse query(IntelligenceResultQueryRequest resultQueryRequest) throws Exception {
        return null;
    }

    @Override
    public String getReconKey(IntelligenceCreditRequest intelligencecreditRequest) throws Exception {
        //无卡快捷间连，通过esb，对账key为
        String esbSequenceNumber = null;
        if (!StringUtil.isEmptyOrNull(intelligencecreditRequest.getAdditionInfo())) {
            JSONObject jsonObject = JSON.parseObject(intelligencecreditRequest.getAdditionInfo());
            if (null != jsonObject) {
                esbSequenceNumber = jsonObject.getString(ShareParamConstant.ESB_SEQUENCE_NUMBER);
            }
        }
        if (!StringUtil.isEmptyOrNull(esbSequenceNumber)) {
            return esbSequenceNumber;
        } else {
            rglog.error("无esb流水号，交易失败");
            throw new BizException(SmartRouteRspEnums.TRANS_FAIL.getRespCode(), SmartRouteRspEnums.TRANS_FAIL.getRespDesc());
        }
    }
}
